﻿/*********************************************************************************
 *Author:         OnClick
 *Version:        1.0
 *UnityVersion:   2017.2.3p3
 *Date:           2019-03-14
 *Description:    IFramework
 *History:        2018.11--
*********************************************************************************/
using System;
using System.Collections.Generic;

namespace IFramework
{
    public abstract class ObjectPool<T> : IObjectPool<T>, IDisposable
    {
        protected int capcity;
        protected Queue<T> pool;
        protected LockParam lockParam;
        public int Capcity { get { return capcity; } set { capcity = value; } }
        public int Count { get { return pool.Count; } }
        public ObjectPool()
        {
            pool = new Queue<T>();
            lockParam = new LockParam();
        }
        public ObjectPool(int capcity) : this()
        {
            this.capcity = capcity;
        }
        public virtual void Dispose()
        {
            using (LockWait wait = new LockWait(ref lockParam))
            {
                while (pool.Count > 0)
                {
                    pool.Dequeue();
                }
            }
        }

        protected abstract T CreatNew();
        public virtual T Get()
        {
            using (LockWait wait = new LockWait(ref lockParam))
            {
                if (pool.Count > 0)
                {
                    return pool.Dequeue();
                }
                return CreatNew();
            }
        }
        public virtual void Set(T t)
        {
            using (LockWait wait = new LockWait(ref lockParam))
            {
                if (!pool.Contains(t))
                {
                    pool.Enqueue(t);
                }
                else
                {
                    throw new Exception("Set Err");
                }
            }
        }
        public virtual void Clear() { }
    }

}
